<?php
// +----------------------------------------------------------------------
// | Author: July
// +----------------------------------------------------------------------
// | 创建时间: 2023-12-27 20:39:42
// +----------------------------------------------------------------------
// | 后台首页控制器
// +----------------------------------------------------------------------

namespace july\julyadmin\admin\controller;

use july\julyadmin\admin\controller\Common;
use july\julyadmin\common\model\Admin as AdminModel;
use july\julyadmin\common\model\Menu as MenuModel;
use think\facade\Db;

class Index extends Common
{
    protected $AdminModel;

    //配置
    private $config;

    //不需要登录验证的控制器和方法，如：['index']
    protected $noNeedLogin = ['login', 'code'];
    //不需要权限验证的控制器和方法，如：['index']
    protected $noPermissionAuth = ['index', 'main', 'logOut'];

    public function __construct()
    {
        //重新初始化父类
        parent::initialize();

        $this->AdminModel = new AdminModel();

        //读取配置
        $config       = \july\julyadmin\common\model\Config::config('System');
        $this->config = $config;
    }

    /**
     * 首页
     */
    public function index()
    {
        if (!session("admininfo")) {
            $this->error("请重新登陆！", url("Index/Login"));
        }

        //查询菜单
        $menus         = MenuModel::menuTree();
        $topLeftMenus  = MenuModel::menuTree(0, ['is_top_left' => 1]);
        $topRightMenus = MenuModel::menuTree(0, ['is_top_right' => 1]);
        return view('index/index', ['menus' => $menus, 'topLeftMenus' => $topLeftMenus, 'topRightMenus' => $topRightMenus, 'config' => $this->config]);
    }

    /**
     * 首页主体
     */
    public function main()
    {
        //服务器信息
        $sys_info['os']   = PHP_OS;
        $sys_info['zlib'] = function_exists('gzclose') ? '是' : '否';

        $sys_info['timezone']       = function_exists("date_default_timezone_get") ? date_default_timezone_get() : "no_timezone";
        $sys_info['curl']           = function_exists('curl_init') ? '是' : '否';
        $sys_info['web_server']     = request()->server('SERVER_SOFTWARE');
        $sys_info['user_agent']     = request()->server('HTTP_USER_AGENT');
        $sys_info['php_version']    = phpversion();
        $sys_info['ip']             = request()->ip();
        $sys_info['fileupload']     = @ini_get('upload_max_filesize') ?: '未知';
        $sys_info['sys_time']       = date('Y-m-d H:i:s', time());
        $sys_info['max_ex_time']    = @ini_get("max_execution_time") . 's';
        $sys_info['set_time_limit'] = function_exists("set_time_limit") ? true : false;
        $sys_info['domain']         = request()->host();
        $sys_info['memory_limit']   = ini_get('memory_limit');
        $mysqlinfo                  = Db::query('select VERSION() as version');
        $sys_info['mysql_version']  = json_encode($mysqlinfo);
        if (function_exists('gd_info')) {
            $gd                 = gd_info();
            $sys_info['gdinfo'] = $gd['GD Version'];
        } else {
            $sys_info['gdinfo'] = "未知";
        }

        $vars = compact('sys_info');
        return view('index/main', $vars);
    }

    /**
     * 验证码
     */
    public function code()
    {
        return \think\captcha\facade\Captcha::create();
    }

    /**
     * 登录
     * @param string $username 账号
     * @param string $password 密码
     * @param string $code     验证码
     */
    public function login()
    {
        if (request()->ispost()) {
            $data = request()->only([
                'username',
                'password',
                'code',
            ], 'post');

            try {
                validate([
                    'username|登录帐号' => 'require',
                    'password|密码'   => 'require',
                ]);
            } catch (ValidateException $e) {
                return json(['code' => 0, 'msg' => $e->getError()]);
            }
            try {
                if (!isset($data['code']) || !$data['code']) {
                    throw new \Exception("验证码不能为空！", 1);
                } else {
                    if (!captcha_check($data['code'])) {
                        \think\captcha\facade\Captcha::create();
                        throw new \Exception("验证码错误！", 1);
                    }
                }
                $pattern = "/^[a-zA-Z\d@._]*$/i";
                if (!preg_match($pattern, $data['username'])) {
                    throw new \Exception("用户名格式错误！", 1);
                }

                $pattern = "/^[a-zA-Z\d]*$/i";
                if (!preg_match($pattern, $data['password'])) {
                    throw new \Exception("密码格式错误！", 1);
                }

                $admininfo = $this->AdminModel->hasWhere('role', ['disabled' => 1])->with('role')->where(['username' => $data['username']])->find();
                if (!$admininfo) {
                    throw new \Exception("账号不存在！", 1);
                }

                if (!$admininfo->disabled) {
                    throw new \Exception("账号被禁用！", 1);
                }
                if ($admininfo->password != md5(md5($data['password']) . $admininfo->encrypt)) {
                    throw new \Exception("密码错误！", 1);
                }

                $data                  = [];
                $data['lastloginip']   = request()->ip();
                $data['lastlogintime'] = date('Y-m-d H:i:s');
                $this->AdminModel->where(['id' => $admininfo->id])->save($data);
                session("admininfo", $admininfo);
                return json(['code' => 1, 'msg' => '登录成功！']);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
        } else {
            return view('index/login' . $this->config['admin_login_template'], ['config' => $this->config]);
        }
    }

    //退出登陆
    public function logOut()
    {
        session("admininfo", null);
        echo '<script>location.href = "' . url("Index/Login") . '";</script>';
    }
}
